package com.gis.controller;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.gis.exception.CustomException;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gis.entity.WaterQualityData;
import com.gis.result.ResponseResult;
import com.gis.service.WaterQualityDataService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;

import static com.gis.maps.commonMap.getParam;
import static com.gis.maps.commonMap.getSeason;


@RestController
@RequiredArgsConstructor
@RequestMapping("/water_quality_data")
@CrossOrigin(origins = "*")
@Tag(name = "水质", description = "水质数据接口")
public class WaterQualityDataController {
    @Autowired
    private WaterQualityDataService waterQualityDataService;

    @Operation(summary = "批量添加水质数据")
    @Parameters({
        @Parameter(name = "waterQualityDataList", description = "水质数据列表", required = true)
    })
    @PostMapping("/addBatch")
    public ResponseResult<String> AddWaterQualityDataServeice(@RequestBody List<WaterQualityData> waterQualityDataList) {
        waterQualityDataService.saveBatch(waterQualityDataList);
        // waterQualityDataService.save(waterQualityData);
        return ResponseResult.success("insert successfully");
    }


    

    @Operation(summary = "获取所有水质数据")
    @GetMapping("/all")
    public ResponseResult<List<WaterQualityData>> GetAllWaterQualityData() {
        List<WaterQualityData> waterQualityDatas = waterQualityDataService.list();
        return ResponseResult.success(waterQualityDatas);
    }

    @Operation(summary = "根据年份和季度获取水质数据")
    @Parameters({
        @Parameter(name = "year", description = "年份", required = true),
        @Parameter(name = "season", description = "季度", required = true)
    })
    @GetMapping("/getByTime")
    public ResponseResult<List<WaterQualityData>> GetByTime(@RequestParam Integer year, @RequestParam String season) {
        QueryWrapper<WaterQualityData> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("year", year).eq("season", season);
        List<WaterQualityData> waterQualityDatas = waterQualityDataService.list(queryWrapper);
        return ResponseResult.success(waterQualityDatas);
    }
    
    @Operation(summary = "根据站点ID获取水质数据")
    @Parameters({
        @Parameter(name = "stationId", description = "站点ID", required = true)
    })
    @GetMapping("/getByStationId")
    public ResponseResult<List<WaterQualityData>> getByStationId(@RequestParam Integer stationId) {
        QueryWrapper<WaterQualityData> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("station_id", stationId).orderByAsc("year");
        List<WaterQualityData> waterQualityDatas = waterQualityDataService.list(queryWrapper);
        return ResponseResult.success(waterQualityDatas);
    }

    @Operation(summary = "分页获取水质数据")
    @Parameters({
        @Parameter(name = "pageNo", description = "页码", required = true),
        @Parameter(name = "pageSize", description = "每页数量", required = true),
        @Parameter(name = "stationId", description = "站点ID", required = false),
        @Parameter(name = "year", description = "年份", required = false),
        @Parameter(name = "season", description = "季度", required = false)
    })
    @GetMapping("/listPage")
    public ResponseResult<IPage<WaterQualityData>> listPage(Integer pageNo,Integer pageSize, Integer stationId, Integer year, String season) {

        Map<String, Object> params = new HashMap<>();
        params.put("station_id", stationId);
        params.put("year", year);
        params.put("season", season);

        IPage<WaterQualityData> page = new Page<>(pageNo, pageSize, true);
        QueryWrapper<WaterQualityData> queryWrapper = new QueryWrapper<>();
        queryWrapper.allEq(params, false);

        return ResponseResult.success(waterQualityDataService.page(page, queryWrapper));
    }

    @Operation(summary = "更新水质数据")
    @Parameters({
        @Parameter(name = "waterQualityData", description = "水质数据", required = true)
    })
    @PostMapping("/update")
    public ResponseResult<WaterQualityData> updata(@RequestBody WaterQualityData entity) {
        waterQualityDataService.saveOrUpdate(entity);
        return ResponseResult.success(entity);
    }
    
    @Operation(summary = "根据ID删除水质数据")
    @Parameters({
        @Parameter(name = "id", description = "水质数据ID", required = true)
    })
    @PostMapping("/deleteById")
    public ResponseResult<String> deleteById(@RequestBody Object json) {
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(json));
        Integer id = jsonObject.getInteger("id");
        waterQualityDataService.removeById(id);
        return ResponseResult.success("delete successfully");
    }


    @Operation(summary = "获取某参数空间分析图")
    @Parameters({
            @Parameter(name = "param", description = "参数（中文）", required = true),
            @Parameter(name = "year", description = "年", required = true),
            @Parameter(name = "season", description = "季节（中文）", required = true),
            @Parameter(name = "tideStatus", description = "（涨、落）", required = true)

    })
    @GetMapping("getSpatialAnalysis")
    public void getSpatialAnalysis(String param, int year, String season, String tideStatus, HttpServletResponse response) {
        // 封装返回的文件
        try {
            // 1. 设置响应头
            response.setContentType("application/tiff");
            response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Expires", "0");

            // 2. 设置文件名
            String filename = String.format("%s空间分析_%d年%s.tif", param, year, season);
            String encodedFilename = URLEncoder.encode(filename, "UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + encodedFilename);

            // 3. 直接调用service生成TIF并写入输出流
            waterQualityDataService.generateTIF(response.getOutputStream(), getParam(param), year, getSeason(season), tideStatus);
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }



    @Operation(summary = "获取某时间段内数据")
    @Parameters({
            @Parameter(name = "stationId", description = "站点id", required = true),
            @Parameter(name = "fromYear", description = "年", required = true),
            @Parameter(name = "fromSeason", description = "季节（中文）", required = true),
            @Parameter(name = "toYear", description = "年", required = true),
            @Parameter(name = "toSeason", description = "季节（中文）", required = true),
            @Parameter(name = "tideStatus", description = "(涨、落)", required = true)
    })
    @GetMapping("getFromYearAndSeason")
    public ResponseResult<List<WaterQualityData>> getFromYearAndSeason(int stationId, int fromYear, String fromSeason ,int toYear, String toSeason, String tideStatus) {
        List<WaterQualityData> waterQualityDatas = waterQualityDataService.getFromYearAndSeason(stationId, fromYear, getSeason(fromSeason), toYear, getSeason(toSeason), tideStatus);
        if(waterQualityDatas.isEmpty()){
            throw new CustomException("无数据");
        }
        return ResponseResult.success(waterQualityDatas);
    }
    
}
